from django.db import models
import uuid
from django.utils import timezone

# Create your models here.
class User(models.Model):
    #可以为空
    username = models.CharField(max_length=20, verbose_name="用户名",  null=True)
    password = models.CharField(max_length=20, verbose_name="密码",  null=True)
    email = models.CharField(max_length=20, verbose_name="邮箱",  null=True)
    #手机号唯一
    phone = models.CharField(max_length=20, verbose_name="手机号", unique=True)
    #头像,默认users\d8ba61281d3b7b3df4f93d8bd06d9f6.png
    avatar = models.ImageField(upload_to='users/', blank=True, verbose_name="用户头像",  default='users/default.png')
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    balance = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name="账户余额")
    
    class Meta:
        verbose_name = "User"
        verbose_name_plural = "用户"
        ordering = ['-create_time']

class RelationType(models.Model):
    name = models.CharField(max_length=20, unique=True, verbose_name="关系类型")  # 如"父母"
    code = models.CharField(max_length=20, unique=True, verbose_name="关系编码")  # 如"parent"

    def __str__(self):
        return self.name

class IdType(models.Model):
    name = models.CharField(max_length=20, unique=True, verbose_name="证件类型")  # 如"身份证"
    code = models.CharField(max_length=20, unique=True, verbose_name="证件编码")  # 如"idcard"

    def __str__(self):
        return self.name


class Patient(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='patients')
    name = models.CharField(max_length=20)
    relation = models.ForeignKey(RelationType, on_delete=models.PROTECT, verbose_name="关系")
    id_type = models.ForeignKey(IdType, on_delete=models.PROTECT, verbose_name="证件类型")
    id_number = models.CharField(max_length=32)
    card_number = models.CharField(max_length=32)
    phone = models.CharField(max_length=20)
    address = models.CharField(max_length=100, blank=True, null=True)
    is_default = models.BooleanField(default=False)
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.name}({self.relation.name})"


class Sflogin(models.Model):
    uid=models.CharField(max_length=200)
    userid = models.ForeignKey(User, on_delete=models.CASCADE)
    token=models.CharField(max_length=100)
    types=models.IntegerField()
    class Meta:
        db_table = 'sflogin'

class RechargeOrder(models.Model):
    """充值订单模型"""
    ORDER_STATUS_CHOICES = (
        ('pending', '待支付'),
        ('paid', '已支付'),
        ('canceled', '已取消'),
    )
    
    PAYMENT_METHOD_CHOICES = (
        ('alipay', '支付宝'),
        ('wechat', '微信支付'),
    )
    
    order_id = models.CharField(max_length=64, primary_key=True, verbose_name="订单ID")
    patient = models.ForeignKey(Patient, on_delete=models.CASCADE, related_name='recharge_orders', verbose_name="就诊人")
    amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="充值金额")
    status = models.CharField(max_length=20, choices=ORDER_STATUS_CHOICES, default='pending', verbose_name="订单状态")
    payment_method = models.CharField(max_length=20, choices=PAYMENT_METHOD_CHOICES, default='alipay', verbose_name="支付方式")
    payment_time = models.DateTimeField(null=True, blank=True, verbose_name="支付时间")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    trade_no = models.CharField(max_length=64, null=True, blank=True, verbose_name="支付宝交易号")
    
    class Meta:
        verbose_name = "充值订单"
        verbose_name_plural = "充值订单"
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.order_id} - {self.amount}元"
    
    @classmethod
    def generate_order_id(cls):
        """生成订单ID: 年月日时分秒+随机数"""
        now = timezone.now()
        order_id = now.strftime('%Y%m%d%H%M%S') + str(uuid.uuid4().int)[:6]
        return order_id

class PaymentUrl(models.Model):
    """支付URL存储模型"""
    order = models.OneToOneField(RechargeOrder, on_delete=models.CASCADE, primary_key=True, related_name='payment_url', verbose_name="关联订单")
    url = models.TextField(verbose_name="支付链接")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    class Meta:
        verbose_name = "支付链接"
        verbose_name_plural = "支付链接"
        ordering = ['-created_at']
    
    def __str__(self):
        return f"支付链接 - {self.order.order_id}"
